package org.springframework.session;

import java.time.Duration;
import java.util.Map;

import reactor.core.publisher.Mono;

import org.springframework.session.events.SessionDeletedEvent;
import org.springframework.session.events.SessionExpiredEvent;

public class ReactiveMapSessionRepository implements ReactiveSessionRepository<MapSession> {

	private Integer defaultMaxInactiveInterval;

	private final Map<String, Session> sessions;

	public ReactiveMapSessionRepository(Map<String, Session> sessions) {
		if (sessions == null) {
			throw new IllegalArgumentException("sessions cannot be null");
		}
		this.sessions = sessions;
	}

	public void setDefaultMaxInactiveInterval(int defaultMaxInactiveInterval) {
		this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
	}

	@Override
	public Mono<Void> save(MapSession session) {
		return Mono.fromRunnable(() -> {
			if (!session.getId().equals(session.getOriginalId())) {
				this.sessions.remove(session.getOriginalId());
			}
			this.sessions.put(session.getId(), new MapSession(session));
		});
	}

	@Override
	public Mono<MapSession> findById(String id) {
		// @formatter:off
		return Mono.defer(() -> Mono.justOrEmpty(this.sessions.get(id))
				.filter((session) -> !session.isExpired())
				.map(MapSession::new)
				.switchIfEmpty(deleteById(id).then(Mono.empty())));
		// @formatter:on
	}

	@Override
	public Mono<Void> deleteById(String id) {
		return Mono.fromRunnable(() -> this.sessions.remove(id));
	}

	@Override
	public Mono<MapSession> createSession() {
		return Mono.defer(() -> {
			MapSession result = new MapSession();
			if (this.defaultMaxInactiveInterval != null) {
				result.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval));
			}
			return Mono.just(result);
		});
	}
}
